/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.mgt.server.service.system.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.repository.JoinCrudRepository;
import com.iwindplus.boot.domain.dto.MessageDTO;
import com.iwindplus.boot.domain.enums.BizCodeEnum;
import com.iwindplus.boot.domain.enums.EnableStatusEnum;
import com.iwindplus.boot.domain.enums.OperateTypeEnum;
import com.iwindplus.boot.domain.exception.BizException;
import com.iwindplus.boot.redis.manager.SerialNumManager;
import com.iwindplus.mgt.domain.constant.MgtConstant;
import com.iwindplus.mgt.domain.dto.system.ApiWhiteListDTO;
import com.iwindplus.mgt.domain.dto.system.ApiWhiteListSearchDTO;
import com.iwindplus.mgt.domain.enums.MgtCodeEnum;
import com.iwindplus.mgt.domain.enums.MgtCodePrefixEnum;
import com.iwindplus.mgt.domain.vo.system.ApiWhiteListPageVO;
import com.iwindplus.mgt.domain.vo.system.ApiWhiteListVO;
import com.iwindplus.mgt.server.mapper.system.ApiWhiteListMapper;
import com.iwindplus.mgt.server.model.system.ApiWhiteListDO;
import com.iwindplus.mgt.server.service.system.ApiWhiteListService;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * API白名单业务层接口实现类.
 *
 * @author zengdegui
 * @since 2020/3/25
 */

@Service
@CacheConfig(cacheNames = {"apiWhiteList"})
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ApiWhiteListServiceImpl extends JoinCrudRepository<ApiWhiteListMapper, ApiWhiteListDO> implements ApiWhiteListService {

    @Resource
    private SerialNumManager serialNumManager;

    @Resource
    private RedissonClient redissonClient;

    @CacheEvict(allEntries = true)
    @Override
    public boolean save(ApiWhiteListDTO entity) {
        entity.setStatus(EnableStatusEnum.ENABLE);
        // 校验路径是否存在
        this.getNameIsExist(entity.getName());
        this.getApiUrlIsExist(entity.getApiUrl());
        if (CharSequenceUtil.isBlank(entity.getCode())) {
            entity.setCode(this.serialNumManager.getSerialNum(MgtCodePrefixEnum.API_WHITE_LIST_PREFIX.getValue()));
        }
        this.getCodeIsExist(entity.getCode().trim());
        entity.setSeq(this.getNextSeq());
        final ApiWhiteListDO model = BeanUtil.copyProperties(entity, ApiWhiteListDO.class);
        super.save(model);
        entity.setId(model.getId());
        this.sendMsg(OperateTypeEnum.ADD);
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean removeByIds(List<Long> ids) {
        List<ApiWhiteListDO> list = super.listByIds(ids);
        if (CollUtil.isEmpty(list)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        boolean match = list.stream().anyMatch(ApiWhiteListDO::getBuildInFlag);
        if (Boolean.TRUE.equals(match)) {
            throw new BizException(BizCodeEnum.HAS_BUILD_IN_DATA);
        }
        super.removeByIds(ids);
        this.sendMsg(OperateTypeEnum.DELETE);
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean edit(ApiWhiteListDTO entity) {
        ApiWhiteListDO data = super.getById(entity.getId());
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (CharSequenceUtil.isNotBlank(entity.getName()) && !CharSequenceUtil.equals(data.getName(), entity.getName().trim())) {
            this.getNameIsExist(entity.getName().trim());
        }
        if (CharSequenceUtil.isNotBlank(entity.getApiUrl()) && !CharSequenceUtil.equals(data.getApiUrl(), entity.getApiUrl().trim())) {
            this.getApiUrlIsExist(entity.getApiUrl().trim());
        }
        if (CharSequenceUtil.isNotBlank(entity.getCode()) && !CharSequenceUtil.equals(data.getCode(), entity.getCode().trim())) {
            this.getCodeIsExist(entity.getCode().trim());
        }
        if (Objects.isNull(entity.getVersion())) {
            entity.setVersion(data.getVersion());
        }
        final ApiWhiteListDO model = BeanUtil.copyProperties(entity, ApiWhiteListDO.class);
        super.updateById(model);
        this.sendMsg(OperateTypeEnum.MODIFY);
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean editStatus(Long id, EnableStatusEnum status) {
        ApiWhiteListDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (status.equals(data.getStatus())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        ApiWhiteListDO param = new ApiWhiteListDO();
        param.setId(id);
        param.setStatus(status);
        param.setVersion(data.getVersion());
        super.updateById(param);
        this.sendMsg(OperateTypeEnum.MODIFY);
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean editBuildIn(Long id, Boolean buildInFlag) {
        ApiWhiteListDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (buildInFlag.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        ApiWhiteListDO param = new ApiWhiteListDO();
        param.setId(id);
        param.setBuildInFlag(buildInFlag);
        param.setVersion(data.getVersion());
        super.updateById(param);
        this.sendMsg(OperateTypeEnum.MODIFY);
        return Boolean.TRUE;
    }

    @Override
    public IPage<ApiWhiteListPageVO> page(ApiWhiteListSearchDTO entity) {
        PageDTO<ApiWhiteListDO> page = new PageDTO<>(entity.getCurrent(), entity.getSize());
        page.setOptimizeCountSql(Boolean.FALSE);
        page.setOptimizeJoinOfCountSql(Boolean.FALSE);
        LambdaQueryWrapper<ApiWhiteListDO> queryWrapper = Wrappers.lambdaQuery(ApiWhiteListDO.class)
            .orderByDesc(ApiWhiteListDO::getModifiedTime);
        if (Objects.nonNull(entity.getStatus())) {
            queryWrapper.eq(ApiWhiteListDO::getStatus, entity.getStatus());
        }
        if (CharSequenceUtil.isNotBlank(entity.getCode())) {
            queryWrapper.eq(ApiWhiteListDO::getCode, entity.getCode().trim());
        }
        if (CharSequenceUtil.isNotBlank(entity.getName())) {
            queryWrapper.eq(ApiWhiteListDO::getName, entity.getName().trim());
        }
        if (CharSequenceUtil.isNotBlank(entity.getApiUrl())) {
            queryWrapper.like(ApiWhiteListDO::getApiUrl, entity.getApiUrl().trim());
        }
        final PageDTO<ApiWhiteListDO> modelPage = super.page(page, queryWrapper);
        return modelPage.convert(model -> BeanUtil.copyProperties(model, ApiWhiteListPageVO.class));
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<String> listApi() {
        LambdaQueryWrapper<ApiWhiteListDO> queryWrapper = Wrappers.lambdaQuery(ApiWhiteListDO.class)
            .eq(ApiWhiteListDO::getStatus, EnableStatusEnum.ENABLE)
            .select(ApiWhiteListDO::getApiUrl)
            .orderByAsc(List.of(ApiWhiteListDO::getApiUrl));
        List<ApiWhiteListDO> list = super.list(queryWrapper);
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        return list.stream().map(ApiWhiteListDO::getApiUrl).distinct().collect(Collectors.toCollection(ArrayList::new));
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public ApiWhiteListVO getDetail(Long id) {
        ApiWhiteListDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        ApiWhiteListVO result = BeanUtil.copyProperties(data, ApiWhiteListVO.class);
        return result;
    }

    private void getNameIsExist(String name) {
        QueryWrapper<ApiWhiteListDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApiWhiteListDO::getName, name);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (result) {
            throw new BizException(MgtCodeEnum.IP_EXIST);
        }
    }

    private void getApiUrlIsExist(String apiUrl) {
        final LambdaQueryWrapper<ApiWhiteListDO> queryWrapper = Wrappers.lambdaQuery(ApiWhiteListDO.class)
            .eq(ApiWhiteListDO::getApiUrl, apiUrl);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.URL_EXIST);
        }
    }

    private void getCodeIsExist(String code) {
        final LambdaQueryWrapper<ApiWhiteListDO> queryWrapper = Wrappers.lambdaQuery(ApiWhiteListDO.class)
            .eq(ApiWhiteListDO::getCode, code);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.CODE_EXIST);
        }
    }

    /**
     * 查询下一个排序号.
     *
     * @return Integer
     */
    private Integer getNextSeq() {
        QueryWrapper<ApiWhiteListDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("max(seq) as seq");
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(queryWrapper, function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }

    private void sendMsg(OperateTypeEnum operateType) {
        try {
            final MessageDTO messageDTO = new MessageDTO();
            messageDTO.setOperateType(operateType);
            final RTopic rTopic = this.redissonClient.getTopic(MgtConstant.TOPIC_API_WHITE_LIST);
            rTopic.publishAsync(messageDTO);
            log.info("发送redis API白名单 topic 成功={}", messageDTO);
        } catch (Exception ex) {
            log.error("redis API白名单 topic Exception={}", ex);
        }
    }
}
